<!--
*@Author: QWP
*@Description: 出差人员选择
*@Date: 2023-09-12 11:03:29
-->
<template>
  <u-dialog title="人员选择"
            top="0"
            v-bind="$attrs"
            v-on="$listeners"
            :hideBtns="isCheck ? ['confirm', ] : []"
            custom-class="u-ccPeople-dialog"
            @submit="submit"
            @close="dialogClose">
    <el-form class="f-w-100">
      <el-row>
        <el-col>
          <el-header style="padding: 0 0 5px 0; height: auto ">
            <el-alert show-icon
                      title="注：非本单位的外来人员，请在【其他外来人员】科室中选择"
                      type="warning"
                      :closable="false">
            </el-alert>
          </el-header>
        </el-col>
      </el-row>
      <el-row class="cc-people-container">
        <el-col :span="8" style="margin-left: -5px">
          <el-aside style="width: auto">
            <el-container>
              <el-header class="s-bg-white  f-padding-12 f-flex-row"
                         style="justify-content: space-between; align-items: center;">
                <el-dropdown>
                  <el-button type="primary" size="small" plain>
                    常用联系人 <i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <u-tree :data="constanceUsers"
                            title=""
                            ref="common"
                            show-checkbox
                            node-key="fkcontactuserid"
                            :isFilter="false"
                            :check-on-click-node="true"
                            :props="{label: 'contactusername'}"
                            placeholder="请输入姓名或拼音"
                            @check-change="evectionTreeCheck"
                            style="width: 200px;" />
                  </el-dropdown-menu>
                </el-dropdown>

                <el-checkbox v-model="allConstance" @change="selectCommonAll" v-if="!isCheck">全选常用</el-checkbox>
              </el-header>
              <el-main class="f-padding-0">
                <u-tree title="" v-if="refresh"
                        ref="tree"
                        show-checkbox
                        :check-on-click-node="true"
                        :check-strictly="true"
                        :render-after-expand="false"
                        :data="getEvectionUserTree"
                        :default-expanded-keys="getEvectionUserDept"
                        @check-change="evectionTreeCheck" />
              </el-main>
            </el-container>
          </el-aside>
        </el-col>
        <el-col style="flex-grow: 1;margin-right: -10px" :span="16">
          <el-main class="s-bg-white f-h-100">
            <u-table :columns="columns"
                     :data="evectionTab"
                     :loading="loading"
                     @link="rowLink"
                     @change="tabChange" />
          </el-main>
        </el-col>
      </el-row>
    </el-form>
  </u-dialog>
</template>
<script>
import common_contactService from '@/service/system/common_contact.service';
import { createNamespacedHelpers } from 'vuex';

const { mapGetters } = createNamespacedHelpers('loginStore');
import { disableTreeKeyid, getDataIdById, getItemByIds } from '@/util/format.ts'
import { nullC, numberC, jsonCopy } from '@/util/commonVerify';

export default {
  components: {},
  props: {
    checkUsers: {
      type: Array,
      default: () => []
    },
    isCheck: {
      type: Boolean,
      default: false
    },
    isBx: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      refresh: true,
      loading: false,
      // 常用联系人
      allConstance: '',
      constanceUsers: [],
      // constUserDChecks: [], // 默认勾中

      // 部门人员树
      isEcho: false,

      evectionTab: [],
      columns: [
        { type: 'index', width: 30, align: 'center', label: '序号' },
        { label: '操作', width: 50, key: 'remove1', icon: 'remove', align: 'center' },
        { label: '所在科室', width: '120', key: 'redeptname' },
        { label: '姓名', width: '120', key: 'reusername' },
        { label: '是否驾驶员', width: '120', key: 'isdriver', ctype: 'switch', align: 'center' },
        {
          label: '标记常用联系人', minWidth: '150', key: 'isconstance', align: 'center', ctype: 'checkbox',
          'true-label': '1', 'false-label': '0'
        }
      ],

      isInit: false
    };
  },
  computed: {
    ...mapGetters(['getUserInfo']),
    getEvectionUserTree() {
      const evectionUser = this.$store.getters['baseStore/get_EVECTION_DEPT_USER'];
      // 设置禁止选择的数据
      let disData = disableTreeKeyid(jsonCopy(evectionUser), 0, 'nodeType') || [];
      return disData;
    },
    getEvectionUserDept() {
      return [this.getUserInfo['deptId']];
    }
  },
  mounted() {
  },
  methods: {
    // 获取常用联系人
    getConstanceUser() {
      this.loading = true;
      return common_contactService.queryByUserId(nullC(this.$store.getters['loginStore/getUserInfo']['userId']))
        .then(res => {
          this.loading = false;
          if (res.data.code == 0) {
            const data = res.data.data;
            data.forEach(item => item.name = item.contactusername);
            this.constanceUsers.splice(0, this.constanceUsers.length, ...data);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 获取出差人员
    getEvectionTreeData() {
      // 设置禁止选择的数据
      let disData = this.getEvectionUserTree;

      // 回显已选中的人员
      this.checkUsers.forEach(item => {
        let treeUser = getItemByIds(disData, [item.fkuserid]);
        let isConstanceUser = this.constanceUsers.findIndex(cItem => cItem.fkcontactuserid == item.fkuserid);
        if (treeUser.length > 0) {
          let tUser = treeUser[0];
          let parentData = getItemByIds(disData, [tUser.fkparentid]);
          let result = {
            isdriver: `${numberC(item['isdriver'])}`, // 0 否    1 是
            ispayee: `${numberC(item['ispayee'])}`, // 是否收款人 0 否    1 是
            fkdeptid: nullC(tUser['fkparentid']),
            fkuserid: nullC(item['fkuserid']),
            redeptname: parentData.length == 0 ? '' : parentData[0]['name'],
            reusername: nullC(tUser.name),
            exa: tUser.exa,
            isconstance: isConstanceUser == -1 ? '0' : '1',
            remove: '<i class=\'iconfont icon-shanchu f-cursor u-icon-danger\'></i>'
          };
          this.evectionTab.push(result);
        }
      });

      let ids = this.checkUsers.map(item => item.fkuserid);
      this.$nextTick(() => {
        this.isEcho = true;
        // 勾选已选择的树
        if (this.$refs.tree.$refs.tree) {
          this.$refs.tree.$refs.tree.setCheckedKeys(ids, true);
        }

        // 勾选已选择常用联系人的树
        if (this.$refs.common.$refs.tree) {
          this.$refs.common.$refs.tree.setCheckedKeys(ids, true);
        }

        setTimeout(() => {
          this.isEcho = false;
        }, 500);
      });
    },

    // 其他出差人员的选择
    evectionTreeCheck(data, cheched) {
      if (this.isEcho == true) {
        return;
      }

      // 判断勾选全选框
      let commonSelected = this.$refs.common.$refs.tree.getCheckedKeys();
      this.allConstance = commonSelected.length == this.constanceUsers.length && commonSelected.length != 0;

      // 选中的人员id
      const fkuserid = data['fkdeptid'] ? data['fkcontactuserid'] : data['keyid'];

      // 判断是否已经在列表中
      let index = this.evectionTab.findIndex(item => item.fkuserid == fkuserid);

      // 选中
      if (cheched == true) {
        const fkparentid = data.fkparentid ? data.fkparentid : data.fkdeptid;
        const treeNode = this.$refs.tree.$refs.tree.getNode(fkparentid);

        let parentData = treeNode ? treeNode['data'] : { name: '' };

        // 是否是常用联系人
        let isConstanceUser = this.constanceUsers.findIndex(item => item.fkcontactuserid == fkuserid);

        // 是否是司机
        let isDrivers = this.checkUsers.filter(item => item.fkuserid == fkuserid);

        if (index == -1) {
          let result = {
            isdriver: isDrivers.length == '0' ? '0' : isDrivers[0]['isdriver'] + '', // 0 否    1 是
            ispayee: isDrivers.length == '0' ? '0' : isDrivers[0]['ispayee'] + '', // 0 否    1 是
            fkdeptid: fkparentid,
            fkuserid: fkuserid,
            redeptname: parentData['name'],
            reusername: data.name,
            exa: data.exa,
            isconstance: isConstanceUser == -1 ? '0' : '1',
            remove: '<i class=\'iconfont icon-shanchu f-cursor u-icon-danger\'></i>'
          };
          this.evectionTab.push(result);
        }
      }
      // 取消勾选
      else {
        if (index != -1) {
          this.evectionTab.splice(index, 1);
        }
      }

      this.$nextTick(() => {
        this.$refs.tree.$refs.tree.setChecked(fkuserid, cheched);
        this.$refs.common.$refs.tree.setChecked(fkuserid, cheched);
      });
    },

    // 全选字段
    selectCommonAll() {
      let selecteds = this.constanceUsers.map(item => item.fkcontactuserid);
      this.$refs.common.$refs.tree.setCheckedKeys(this.allConstance ? selecteds : []);
    },

    // 提交信息
    submit() {
      this.$emit('save', JSON.parse(JSON.stringify(this.evectionTab)));
    },

    // 行点击事件
    rowLink(key, data, row) {
      //  点击出差人
      if (key == 'remove1') {
        this.evectionTreeCheck({ 'keyid': row.fkuserid }, false);
      }
    },

    // 列表的change、事件
    tabChange(key, data, row, rowIndex) {
      if (key == 'isconstance') {
        const url = row.isconstance == '1' ? 'add' : 'deleteContact';

        const form = url == 'add' ? {
          fkuserid: this.$store.getters['loginStore/getUserInfo']['userId'],
          fkcontactuserid: row.fkuserid
        } : { contactUserId: row.fkuserid };


        common_contactService[url](form).then(res => {
          if (res.data.code == 0) {
            this.getConstanceUser();
          }
        })
          .catch(() => {
          });
      }

      // 主报销人，多个是控制
      if (key == 'ispayee' && row[key] == 1) {
        let isMainBxs = this.evectionTab.filter(item => item.ispayee == 1);
        if (isMainBxs.length != 1) {
          this.evectionTab.splice(rowIndex, 1, { ...this.evectionTab[rowIndex], ispayee: 0 });
          this.$common.alertC('只能有一个主报销人!');
        }
      }
    },

    dialogClose() {
      this.evectionTab.splice(0, this.evectionTab.length);
      this.$refs.tree.$refs.tree.setCheckedKeys([]);
      this.$refs.common.$refs.tree.setCheckedKeys([]);
    }

  },
  watch: {
    async '$attrs.show'(nval) {
      if (nval == true) {
        await this.getConstanceUser();
        this.getEvectionTreeData();
        let isExistMainBx = this.columns.findIndex(item => item.key == 'ispayee');
        if (this.isBx == true && isExistMainBx == -1) {
          this.columns.splice(2, 0, {
            label: '主报销人',
            width: '120',
            key: 'ispayee',
            ctype: 'switch',
            align: 'center'
          });
        }
      }
    }
  }
};
</script>
<style></style>

<style lang="scss">
.u-ccPeople-dialog {
  float: right;

  .title {
    background: #E6A23C;

    p {
      height: 32px;
      line-height: 32px;
      padding-left: 14px;
      color: #E7EEFF;
    }
  }

  .el-checkbox.is-disabled {
    display: none;
  }

  .cc-people-container {
    display: flex;
    gap: 5px;
  }
}

.u-loading-box {
  display: flex;
}
</style>

